package com.pxmeta.app.controller.user;

import cn.dev33.satoken.annotation.SaCheckLogin;
import cn.dev33.satoken.stp.StpUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.google.common.collect.Maps;
import com.pxmeta.chat.entity.dto.SetDisturbDTO;
import com.pxmeta.chat.entity.vo.ChatUserVO;
import com.pxmeta.chat.service.HuanxinService;
import com.pxmeta.circle.entity.dto.SignInDTO;
import com.pxmeta.common.constant.HttpStatus;
import com.pxmeta.common.core.domain.AjaxResult;
import com.pxmeta.common.enums.ContentAuditEnum;
import com.pxmeta.common.utils.SecurityUtils;
import com.pxmeta.common.utils.StringUtils;
import com.pxmeta.dynamic.entity.dto.BlockUserDTO;
import com.pxmeta.dynamic.entity.dto.DynamicDTO;
import com.pxmeta.dynamic.entity.dto.ReportUserDTO;
import com.pxmeta.dynamic.service.IDynamicService;
import com.pxmeta.user.entity.User;
import com.pxmeta.user.entity.UserPhoto;
import com.pxmeta.user.entity.dto.SavePhotoDTO;
import com.pxmeta.user.entity.dto.UpdateRecommendConfigDTO;
import com.pxmeta.user.entity.dto.UserDTO;
import com.pxmeta.user.entity.vo.UserBalanceVO;
import com.pxmeta.user.entity.vo.UserVO;
import com.pxmeta.user.service.*;
import com.pxmeta.verify.service.VerifyService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.math.BigDecimal;
import java.util.*;

import static com.pxmeta.common.constant.KiteConstant.DEFAULT_PASSWORD;

@RestController
@RequestMapping("/user")
@RequiredArgsConstructor
@Api(value = "用户中心",tags = "用户中心")
@Slf4j
public class UserController {
    private final IUserService userService;
    private final IDynamicService dynamicService;
    private final IUserBlockService userBlockService;
    private final IUserReportService userReportService;
    private final HuanxinService huanxinService;
    private final IUserFollowService userFollowService;
    private final VerifyService verifyService;
    private final IUserPhotoService userPhotoService;

    @SaCheckLogin
    @ApiOperation("用户详情")
    @GetMapping("/detail")
    public AjaxResult<UserDTO> getUserInfo(@RequestParam(required = false) Long userId){
        Long selfUserId = SecurityUtils.getUserId();
        userId = userId == null ? selfUserId : userId;
        UserDTO user =  userService.getUserInfo(selfUserId,userId);
        return AjaxResult.success(user);
    }

    @SaCheckLogin
    @ApiOperation("用户详情")
    @GetMapping("/getUserInfoByAccount")
    public AjaxResult<User> getUserInfoByAccount(@RequestParam String account){
        User user = userService.getByAccount(account);
        return AjaxResult.success(user);
    }


    @SaCheckLogin
    @ApiOperation("修改个性化推荐")
    @PutMapping(value = "/updateRecommendConfig")
    public AjaxResult updateRecommendConfig(@RequestBody UpdateRecommendConfigDTO dto){

        Long userId = SecurityUtils.getUserId();
        User user = userService.getById(userId);
        user.setIsOpenRecommend(dto.getIsOpenRecommend());
        userService.updateById(user);
        return AjaxResult.success();
    }

    @SaCheckLogin
    @ApiOperation("保存照片墙")
    @PostMapping(value = "/savePhotos")
    public AjaxResult savePhotos(@RequestBody SavePhotoDTO dto){

        Long userId = SecurityUtils.getUserId();
        userPhotoService.saveUserPhotos(userId, dto.getPhotos());
        return AjaxResult.success();
    }

    @SaCheckLogin
    @ApiOperation("删除照片墙")
    @DeleteMapping(value = "/deletePhotos")
    public AjaxResult deletePhotos(@RequestParam Long photoId){
        userPhotoService.removeById(photoId);
        return AjaxResult.success();
    }


    @SaCheckLogin
    @ApiOperation("查看用户照片墙")
    @GetMapping(value = "/listPhotos")
    public AjaxResult listPhotos(@RequestParam Long userId){

        LambdaQueryWrapper<UserPhoto> wrapper = Wrappers.lambdaQuery();
        wrapper.eq(UserPhoto::getUserId, userId)
                .orderByDesc(UserPhoto::getSort)
                .orderByDesc(UserPhoto::getCreateTime);
        List<UserPhoto> list = userPhotoService.list(wrapper);
        return AjaxResult.success(list);
    }

    @SaCheckLogin
    @GetMapping("/bindInviteCode")
    @ApiOperation("绑定邀请码")
    public AjaxResult bindInviteCode(@RequestParam String inviteCode){
        Long userId = SecurityUtils.getUserId();
        userService.bindUserByInviteCode(userId,inviteCode);
        return AjaxResult.success();
    }



    @SaCheckLogin
    @ApiOperation("获取用户金币余额")
    @GetMapping("/getBalance")
    public AjaxResult<UserBalanceVO> getBalance(){
        Long userId = SecurityUtils.getUserId();
        User user = userService.getById(userId);
        BigDecimal balance = user.getBalance();
        UserBalanceVO vo = UserBalanceVO.builder().balance(balance).build();
        return AjaxResult.success(vo);
    }

    @SaCheckLogin
    @ApiOperation("个人动态")
    @GetMapping("/getMyDynamic")
    public AjaxResult getMyDynamic(@RequestParam(required = false,defaultValue = "1") Integer page,
                                   @RequestParam(required = false,defaultValue = "20") Integer size){
        Long userId = SecurityUtils.getUserId();
        List<DynamicDTO> dynamicList = dynamicService.getByUserId(userId, page, size);
        return AjaxResult.success(dynamicList);
    }



    @SaCheckLogin
    @PostMapping("/updateUser")
    @ApiOperation("修改用户信息")
    @SneakyThrows
    public AjaxResult updateUser(@RequestBody User user){
        if (StringUtils.isNotBlank(user.getNickname())){
            String audit = verifyService.auditText(user.getNickname());
            if (ContentAuditEnum.BLOCK.getSuggestion().equals(audit)){
                user.setNickname("违规昵称");
            }
        }
        if (StringUtils.isNotBlank(user.getAvatar())){
            String audit = verifyService.auditImg(Collections.singletonList(user.getAvatar()));
            if (ContentAuditEnum.BLOCK.getSuggestion().equals(audit)){
                user.setAvatar("https://pengxinapp.oss-cn-beijing.aliyuncs.com/register_head/img_man1.png");
            }
            if (ContentAuditEnum.REVIEW.getSuggestion().equals(audit)){
                user.setAvatar("https://pengxinapp.oss-cn-beijing.aliyuncs.com/register_head/img_man1.png");
            }
        }
        if (StringUtils.isNotBlank(user.getIntro())){
            String audit = verifyService.auditText(user.getIntro());
            if (ContentAuditEnum.BLOCK.getSuggestion().equals(audit)){
                user.setIntro("暂无");
            }
        }

        userService.bindUserByInviteCode(user.getId(), user.getInviteCode());
        if (StringUtils.isNotBlank(user.getAbout())){
            String audit = verifyService.auditText(user.getAbout());
            if (ContentAuditEnum.BLOCK.getSuggestion().equals(audit)){
                user.setAbout("暂无");
            }
        }
        userService.updateById(user);
        //todo 同步环信
        User finalUser = userService.getById(user.getId());
        ChatUserVO userVo = new ChatUserVO();
        userVo.setAvatarUrl(user.getAvatar());
        userVo.setUserId(user.getId());
        userVo.setGender(user.getSex());
        userVo.setBirth(user.getBirthday());
        userVo.setNickName(user.getNickname());
        huanxinService.updateUser(userVo,finalUser.getUsername());
        return AjaxResult.success();
    }



    @SaCheckLogin
    @ApiOperation("初始化用户信息")
    @PostMapping("/initUser")
    @SneakyThrows
    public AjaxResult initUser(@RequestBody @Valid UserVO vo){
        String code = vo.getInviteCode();
        vo.setInviteCode(null);
        Long userId = SecurityUtils.getUserId();
        User user = new User();
        if (StringUtils.isBlank(vo.getAvatar())
                &&StringUtils.isBlank(vo.getNickname())
                &&vo.getBirthday() == null
                && vo.getSex() == null){
            return AjaxResult.error(HttpStatus.PARAMS_ERROR, "参数不能为空！");
        }
        vo.setId(userId);
        BeanUtils.copyProperties(vo, user);
        boolean isBlocked = false;
        if (StringUtils.isNotBlank(user.getNickname())){
            String audit = verifyService.auditText(user.getNickname());
            if (ContentAuditEnum.BLOCK.getSuggestion().equals(audit)){
                user.setNickname("违规昵称");
                isBlocked = true;
            }
        }

        if (StringUtils.isNotBlank(user.getIntro())){
            String audit = verifyService.auditText(user.getIntro());
            if (ContentAuditEnum.BLOCK.getSuggestion().equals(audit)){
                user.setIntro("暂无");
                isBlocked = true;
            }
        }

        if (StringUtils.isNotBlank(user.getAvatar())){
            String audit = verifyService.auditImg(Arrays.asList(user.getAvatar()));
            if (ContentAuditEnum.BLOCK.getSuggestion().equals(audit)){
                user.setAvatar("https://pengxinapp.oss-cn-beijing.aliyuncs.com/register_head/img_man1.png");
                isBlocked = true;
            }
        }
        if (StringUtils.isNotBlank(user.getAbout())){
            String audit = verifyService.auditText(user.getAbout());
            if (ContentAuditEnum.BLOCK.getSuggestion().equals(audit)){
                user.setAbout("暂无");
            }
        }
        userService.updateById(user);
        User finalUser = userService.getById(userId);

        userService.bindUserByInviteCode(userId, code);

        ChatUserVO userVO = new ChatUserVO();
        userVO.setAvatarUrl(finalUser.getAvatar());
        userVO.setNickName(finalUser.getNickname());
        userVO.setGender(finalUser.getSex());
        userVO.setBirth(finalUser.getBirthday());
        try{
            huanxinService.updateUser(userVO,finalUser.getUsername());
        }catch (Exception e){
            log.info("更新环信用户失败,错误信息：{}",e.getMessage());
        }
        if (isBlocked){
            return AjaxResult.error("内容违规！");
        }

        return AjaxResult.success();
    }


    @SaCheckLogin
    @ApiOperation("拉黑用户")
    @PostMapping("/blockUser")
    public AjaxResult blockUser(@RequestBody BlockUserDTO dto){
        Long userId = SecurityUtils.getUserId();
        userBlockService.blockUser(userId, dto.getBlockUserId());
        return AjaxResult.success();
    }

    @SaCheckLogin
    @ApiOperation("解除拉黑")
    @PostMapping("/unBlockUser")
    public AjaxResult unBlockUser(@RequestBody BlockUserDTO dto){
        Long userId = SecurityUtils.getUserId();
        userBlockService.unBlockUser(userId, dto.getBlockUserId());
        return AjaxResult.success();
    }


    @SaCheckLogin
    @GetMapping("/getUserByUsername")
    @ApiOperation("根据用户名（环信id）获取用户信息")
    public AjaxResult getUserIdByImId(@RequestParam String username){
        User user = userService.getByUsername(username);
        Long userId = user.getId();
        UserDTO userDTO =  userService.getUserInfo(userId,userId);
        return AjaxResult.success(userDTO);
    }


    @SaCheckLogin
    @GetMapping("/disturbCircle")
    @ApiOperation("屏蔽圈子")
    public AjaxResult disturbUser(@RequestBody SetDisturbDTO dto){
        Long userId = SecurityUtils.getUserId();
        userService.disturbCircle(userId,dto);
        return AjaxResult.success();
    }

    @SaCheckLogin
    @PostMapping("/reportUser")
    @ApiOperation("用户举报")
    public AjaxResult reportUser(@RequestBody ReportUserDTO dto) {
        Long userId = SecurityUtils.getUserId();
        userReportService.report(dto,userId);
        return AjaxResult.success("举报成功！");
    }


    @GetMapping(value = "/searchUsers")
    @ApiOperation("搜索用户")
    public AjaxResult<List<User>> searchUsers(@RequestParam Integer page,
                                          @RequestParam Integer size,
                                          @RequestParam String keyword){
        IPage<User> result = userService.searchUser(page, size, keyword);
        return AjaxResult.success(result.getRecords());
    }


    @GetMapping("/getFindObjectUserList")
    @ApiOperation("获取找对象用户列表")
    @SaCheckLogin
    public AjaxResult<List<User>> getFindObjectUserList(@RequestParam String addr,
                                            @RequestParam Integer page,
                                            @RequestParam Integer size){

        List<User> list = userService.getFindObjectUserList(addr, page, size);

        return AjaxResult.success(list);
    }


    @SaCheckLogin
    @GetMapping("/getContacts")
    @ApiOperation("获取联系人")
    public AjaxResult getContracts(){
        Long userId = SecurityUtils.getUserId();
        List<UserDTO> followUsers = userFollowService.getFollowUsers(userId, 1, 100);
        List<UserDTO> fansUsers = userFollowService.getFansUsers(userId, 1, 100);
        List<UserDTO> friendUsers = userFollowService.getFriendUsers(userId, 1, 500, null,null,null);
        Map<String,Object> map = Maps.newHashMap();
        map.put("followUsers",followUsers);
        map.put("fansUsers",fansUsers);
        map.put("friendUsers",friendUsers);
        return AjaxResult.success(map);
    }




}
